<?php

namespace App\Listeners\Kms;

use App\Events\Kms\GroupShareEvent;
use App\Library\FeiShu\SendFs;
use App\Listeners\BaseListener;
use App\Models\Kms\Album\AlbumResourceModel;
use App\Remote\Feishu\FeishuImageRemote;
use App\Service\Common\PreviewService;
use App\Service\Kms\Album\AlbumMainService;
use App\Service\Kms\Common\DateService;
use Illuminate\Support\Collection;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

/**
 * kms 资源分享
 */
class GroupShareListener extends BaseListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Handle the event.
     *
     * @param GroupShareEvent $groupShareEvent
     * @return void
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function handle(GroupShareEvent $groupShareEvent)
    {
        try {
            $saveDir    = getTmpDir("/kms/fsShareGroup/" . formatDateYmd(time()));
            $fileSystem = getFileSystem();
            if (!$fileSystem->isDirectory($saveDir)) {
                $fileSystem->makeDirectory($saveDir, 0777, true);
            }

            $resourceIds      = [];
            $shareImgKeyGroup = AlbumResourceModel::query()
                                                  ->where("mid", $groupShareEvent->mid)
                                                  ->whereIn("id", $groupShareEvent->resourceIds)
                                                  ->get()
                                                  ->map(function (AlbumResourceModel $albumResourceModel, $index) use (
                                                      $fileSystem,
                                                      $saveDir,
                                                      &$resourceIds
                                                  ) {
                                                      $date         = $albumResourceModel->date;
                                                      $weekDay      = $albumResourceModel->weekDay;
                                                      $shootingTime = $albumResourceModel->shootingTime;
                                                      $type         = $albumResourceModel->type;
                                                      $id           = $albumResourceModel->id;

                                                      if ($type == AlbumResourceModel::TYPE_RESOURCE_2) {
                                                          array_push($resourceIds, $albumResourceModel->id);
                                                      }

                                                      if (empty($albumResourceModel->fsImgKey)) {
                                                          switch ($albumResourceModel->type) {
                                                              case AlbumResourceModel::TYPE_RESOURCE_2:
                                                                  $originalResourceUrl = $albumResourceModel->previewUrl;
                                                                  break;
                                                              default:
                                                                  $originalResourceUrl = $albumResourceModel->originalUrl;
                                                                  break;
                                                          }
                                                          $filePath = vsprintf("%s/%s.%s", [
                                                              $saveDir,
                                                              md5($originalResourceUrl),
                                                              (new \SplFileInfo($originalResourceUrl))->getExtension()
                                                          ]);
                                                          $fileSystem->put(
                                                              $filePath,
                                                              file_get_contents($originalResourceUrl)
                                                          );
                                                          $fsImgKey = FeishuImageRemote::uploadImage($filePath)["image_key"];
                                                          $albumResourceModel->setRawAttributes(
                                                              ["fsImgKey" => $fsImgKey]
                                                          )->save();
                                                      } else {
                                                          $fsImgKey = $albumResourceModel->fsImgKey;
                                                      }

                                                      return [
                                                          "id"           => $id,
                                                          "type"         => $type,
                                                          "date"         => $date,
                                                          "weekDay"      => $weekDay,
                                                          "fsImgKey"     => $fsImgKey,
                                                          "shootingTime" => $shootingTime,
                                                          "desc"         => $index + 1
                                                      ];
                                                  })->values()->groupBy("date")
                                                  ->map(function (Collection $v, $date) {
                                                      $shootingTime = $v->getIterator()->current()["shootingTime"];
                                                      $temp         = [
                                                          "list"    => [],
                                                          "date"    => date("Y/m/d H:i:s", $shootingTime),
                                                          "weekDay" => DateService::translateDate($shootingTime)["weekDayCn"]
                                                      ];
                                                      $i            = 0;
                                                      while ($i * 3 < count($v)) {
                                                          array_push($temp["list"],
                                                              array_slice($v->toArray(), $i * 3, 3));
                                                          $i++;
                                                      }
                                                      return $temp;
                                                  })->toArray();


            $previewUrl = "";
            if ($resourceIds) {
                sort($resourceIds, SORT_ASC);
                $queryParams = [
                    "type"        => PreviewService::RESOURCE_SOURCE_1,
                    "resourceIds" => $resourceIds
                ];
                ksort($queryParams);
                $sign        = md5(json_encode($queryParams, JSON_UNESCAPED_UNICODE) . "sign");
                $queryParams = array_merge($queryParams,
                    ["sign" => $sign, "resourceIds" => implode(",", $resourceIds), "title" => "巡店视频"]);
                $previewUrl  = config('webUrl.notify_web_cdn_url') . '#/pages/video-preview/video-preview?' . http_build_query($queryParams);
            }

            $msgTemplateContents = view()->file(
                app_path("Remote/Feishu/FsTemplate/Kms") . "/ChatGroupMsgFsTemplate.blade.php",
                [
                    "shareImgGroup" => $shareImgKeyGroup,
                    "shareUsername" => vsprintf("%s (%s)", [
                        attributeGet($groupShareEvent, "shareUser.name", ""),
                        attributeGet($groupShareEvent, "shareUser.nickname", "")
                    ]),
                    "comment"       => attributeGet($groupShareEvent, "comment", ""),
                    "shareDate"     => date("Y/m/d H:i:s", time()),
                    "total"         => count($groupShareEvent->resourceIds),
                    "previewUrl"    => $previewUrl
                ]
            )->render();


            collect(
                AlbumMainService::groupList(true)["groupList"]
            )->map(function ($v, $key) {
                return array_merge($v, ["id" => $key]);
            })->whereIn("id", $groupShareEvent->groupIds)->each(function ($group) use ($msgTemplateContents) {
                collect($group["robots"] ?? [])->each(function ($fsRobot) use ($msgTemplateContents) {
                    SendFs::newRobot()
                          ->coverConfig($fsRobot["webhook"], $fsRobot["secret"])
                          ->setCardMessageBody(
                              json_decode(str_replace(["\r", "\r\n", PHP_EOL, "  "], "", $msgTemplateContents), true)
                          )->send();
                });
            });
        } catch (\Exception $exception) {
            logException("群消息推送失败", $exception, get_object_vars($groupShareEvent), true, true);
        }
    }
}
